package com.bw.services.activity

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bw.lib_base.base.BaseActivity
import com.bw.services.R
import com.bw.services.databinding.ActivityAddNewsBinding
import com.bw.services.viewmodel.ServicesViewModel
import com.therouter.TheRouter
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint
import android.app.DatePickerDialog
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.bw.services.entity.NewsEntity
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

@AndroidEntryPoint
@Route(path = "app/AddNewsActivity")
class AddNewsActivity : BaseActivity<ActivityAddNewsBinding,ServicesViewModel>() {
    
    private val selectedImages = mutableListOf<Uri>()
    private lateinit var imageAdapter: ImageAdapter
    
    // 图片选择结果处理
    private val imagePickerLauncher = registerForActivityResult(
        ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            selectedImages.add(it)
            updateImageRecyclerView()
        }
    }

    override fun generatePremission(pageName: String): Array<String> {
        return arrayOf()
    }

    override fun setupUI() {
        // 设置新闻类型下拉菜单
        val newsTypes = arrayOf("公司新闻", "行业动态", "通知公告", "活动信息", "其他")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, newsTypes)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinnerType.adapter = adapter
        
        // 初始化图片RecyclerView
        imageAdapter = ImageAdapter(selectedImages) { position ->
            selectedImages.removeAt(position)
            updateImageRecyclerView()
        }
        binding.rvImages.layoutManager = GridLayoutManager(this, 3)
        binding.rvImages.adapter = imageAdapter
        
        // 设置标题输入框的文本变化监听器
        binding.etTitle.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            
            override fun afterTextChanged(s: Editable?) {
                val currentLength = s?.length ?: 0
                val maxLength = 50
                
                // 如果超过最大长度，截取到最大长度
                if (currentLength > maxLength) {
                    s?.delete(maxLength, currentLength)
                    return
                }
                
                // 更新计数器文本
                binding.tvTitleCounter.text = "$currentLength/$maxLength"
                
                // 如果达到最大长度，将计数器文字变红
                if (currentLength >= maxLength) {
                    binding.tvTitleCounter.setTextColor(ContextCompat.getColor(this@AddNewsActivity, R.color.red))
                } else {
                    binding.tvTitleCounter.setTextColor(ContextCompat.getColor(this@AddNewsActivity, R.color.black))
                }
            }
        })
    }

    override fun fetchData() {

        // 获取数据的方法
    }

    override fun observeData() {
        lifecycleScope.launch {
            vm.addNewsData.collect {
                if (it!=null) {
                    ToastUtils.showShort("新闻发布成功")
                    finish()
                }
            }
        }
        // 观察数据变化
    }

    override fun handleEvent() {
        // 返回按钮点击事件
        binding.ivBack.setOnClickListener {
            finish()
        }
        
        // 发布按钮点击事件
        binding.btnSubmit.setOnClickListener {
            publishNews()
        }
        
        // 添加图片按钮点击事件
        binding.btnAddImage.setOnClickListener {
            addImage()
        }
        
        // 发布日期选择器点击事件
        binding.etPublishDate.setOnClickListener {
            showDatePicker()
        }
        
        // 预览按钮点击事件
        binding.btnCancel.setOnClickListener {
            previewNews()
        }
        
        // 测试跳转到ServicesActivity
        binding.imgEye.setOnClickListener {
            TheRouter.build("app/ServicesActivity").navigation(this)
        }
    }
    
    /**
     * 发布新闻
     */
    private fun publishNews() {
        val title = binding.etTitle.text.toString().trim()
        val person = binding.etPerson.text.toString().trim()
        val content = binding.etContent.text.toString().trim()
        val type = binding.spinnerType.selectedItem.toString()
        val publishDate = binding.etPublishDate.text.toString().trim()
        
        if (title.isEmpty()) {
            ToastUtils.showShort("请输入新闻标题")
            return
        }
        
        if (content.isEmpty()) {
            ToastUtils.showShort("请输入新闻内容")
            return
        }
        
        if (publishDate.isEmpty()) {
            ToastUtils.showShort("请选择发布日期")
            return
        }
        
        // 将图片URI转换为字符串列表
        val imageUrls = selectedImages.map { it.toString() }
        
        val news = NewsEntity(
            approved = true,
            content = content,
            id = 0,
            images = imageUrls,
            publishDate = publishDate,
            published = true,
            publisher = person,
            title = title,
            type = type
        )
        lifecycleScope.launch {  vm.get_addNews(news) }

    }
    
    /**
     * 添加图片
     */
    private fun addImage() {
        imagePickerLauncher.launch("image/*")
    }
    
    /**
     * 更新图片RecyclerView
     */
    private fun updateImageRecyclerView() {
        if (selectedImages.isNotEmpty()) {
            binding.rvImages.visibility = android.view.View.VISIBLE
            imageAdapter.notifyDataSetChanged()
        } else {
            binding.rvImages.visibility = android.view.View.GONE
        }
    }
    
    /**
     * 显示日期选择器
     */
    private fun showDatePicker() {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        
        val datePickerDialog = DatePickerDialog(
            this,
            { _, selectedYear, selectedMonth, selectedDay ->
                val selectedCalendar = Calendar.getInstance()
                selectedCalendar.set(selectedYear, selectedMonth, selectedDay)
                
                // 获取当前时间的小时、分钟、秒
                val currentCalendar = Calendar.getInstance()
                val hour = currentCalendar.get(Calendar.HOUR_OF_DAY)
                val minute = currentCalendar.get(Calendar.MINUTE)
                val second = currentCalendar.get(Calendar.SECOND)
                
                // 设置选择的时间
                selectedCalendar.set(Calendar.HOUR_OF_DAY, hour)
                selectedCalendar.set(Calendar.MINUTE, minute)
                selectedCalendar.set(Calendar.SECOND, second)
                
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                val selectedDate = dateFormat.format(selectedCalendar.time)
                
                binding.etPublishDate.setText(selectedDate)
            },
            year,
            month,
            day
        )
        
        datePickerDialog.show()
    }
    
    /**
     * 预览新闻
     */
    private fun previewNews() {
        val title = binding.etTitle.text.toString().trim()
        val person = binding.etPerson.text.toString().trim()
        val content = binding.etContent.text.toString().trim()
        val type = binding.spinnerType.selectedItem.toString()
        val publishDate = binding.etPublishDate.text.toString().trim()
        
        if (title.isEmpty() && content.isEmpty()) {
            ToastUtils.showShort("请先填写新闻内容")
            return
        }
        
        // 创建预览对话框
        val dialogView = android.view.LayoutInflater.from(this).inflate(R.layout.dialog_news_preview, null)
        val dialog = android.app.AlertDialog.Builder(this)
            .setTitle("新闻预览")
            .setView(dialogView)
            .setPositiveButton("确定") { _, _ -> }
            .create()
        
        // 获取对话框中的视图
        val titleView = dialogView.findViewById<android.widget.TextView>(R.id.tv_preview_title)
        val publisherView = dialogView.findViewById<android.widget.TextView>(R.id.tv_preview_publisher)
        val dateView = dialogView.findViewById<android.widget.TextView>(R.id.tv_preview_date)
        val typeView = dialogView.findViewById<android.widget.TextView>(R.id.tv_preview_type)
        val contentView = dialogView.findViewById<android.widget.TextView>(R.id.tv_preview_content)
        val imagesLayout = dialogView.findViewById<android.view.View>(R.id.ll_preview_images)
        val imagesRecyclerView = dialogView.findViewById<RecyclerView>(R.id.rv_preview_images)
        
        // 设置预览内容
        titleView?.text = if (title.isNotEmpty()) title else "未填写标题"
        publisherView?.text = if (person.isNotEmpty()) person else "未填写发布人"
        dateView?.text = if (publishDate.isNotEmpty()) publishDate else "未选择日期"
        typeView?.text = if (type.isNotEmpty()) type else "未选择类型"
        contentView?.text = if (content.isNotEmpty()) content else "未填写内容"
        
        // 设置图片预览
        if (selectedImages.isNotEmpty()) {
            imagesLayout.visibility = android.view.View.VISIBLE
            val previewImageAdapter = PreviewImageAdapter(selectedImages)
            imagesRecyclerView.layoutManager = GridLayoutManager(this, 3)
            imagesRecyclerView.adapter = previewImageAdapter
        } else {
            imagesLayout.visibility = android.view.View.GONE
        }
        
        dialog.show()
    }

    override val mLayoutResId: Int
        get() = R.layout.activity_add_news
}

/**
 * 图片适配器
 */
class ImageAdapter(
    private val images: List<Uri>,
    private val onDeleteClick: (Int) -> Unit
) : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {

    class ImageViewHolder(itemView: android.view.View) : RecyclerView.ViewHolder(itemView) {
        val imageView: android.widget.ImageView = itemView.findViewById(R.id.iv_image)
        val deleteButton: android.widget.ImageButton = itemView.findViewById(R.id.btn_delete)
    }

    override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ImageViewHolder {
        val view = android.view.LayoutInflater.from(parent.context)
            .inflate(R.layout.item_image, parent, false)
        return ImageViewHolder(view)
    }

    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        val imageUri = images[position]
        
        // 加载图片
        holder.imageView.setImageURI(imageUri)
        
        // 设置删除按钮点击事件
        holder.deleteButton.setOnClickListener {
            onDeleteClick(position)
        }
    }

    override fun getItemCount(): Int = images.size
}

/**
 * 预览图片适配器
 */
class PreviewImageAdapter(
    private val images: List<Uri>
) : RecyclerView.Adapter<PreviewImageAdapter.PreviewImageViewHolder>() {

    class PreviewImageViewHolder(itemView: android.view.View) : RecyclerView.ViewHolder(itemView) {
        val imageView: android.widget.ImageView = itemView.findViewById(R.id.iv_preview_image)
    }

    override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): PreviewImageViewHolder {
        val view = android.view.LayoutInflater.from(parent.context)
            .inflate(R.layout.item_preview_image, parent, false)
        return PreviewImageViewHolder(view)
    }

    override fun onBindViewHolder(holder: PreviewImageViewHolder, position: Int) {
        val imageUri = images[position]
        
        // 加载图片
        holder.imageView.setImageURI(imageUri)
    }

    override fun getItemCount(): Int = images.size
}